import { Component, OnInit, ViewChild, Input } from '@angular/core';
import { NzModalRef, NzMessageService, NzNotificationService } from 'ng-zorro-antd';
import { _HttpClient } from '@delon/theme';
import { SFSchema, SFUISchema } from '@delon/form';
import { Observable, of, zip } from 'rxjs';
import { catchError } from 'rxjs/operators';

/**
 * 添加、修改消息元数据
 * @author xiaomin luo
 * @date 2019年12月02日
 */
@Component({
  selector: 'web-message-meta-edit',
  templateUrl: './msg-meta-modal.component.html',
})
export class MsgMetaModalComponent implements OnInit {
  msgTypes = [
    { label: '系统消息', value: 'SYS' },
    { label: '用户消息', value: 'USER' },
  ];
  sysTypes = [];
  @Input()
  record: any = {};
  i: any;
  schema: SFSchema = {
    properties: {},
  };
  ui: SFUISchema = {
    '*': {
      spanLabelFixed: 100,
      grid: { span: 12 },
    },
  };

  constructor(
    private modal: NzModalRef,
    private msgSrv: NzMessageService,
    public http: _HttpClient,
    private notice: NzNotificationService,
  ) {}

  ngOnInit(): void {
    const api = [this.http.get(`/cf/admin/dict/type/msg_type`)];
    zip(...api)
      .pipe(
        catchError(([sysTypes]) => {
          return [sysTypes];
        }),
      )
      .subscribe(([sysTypes]) => {
        this.sysTypes = sysTypes.data;
        this.buildSf();
        if (this.record.id) {
          this.http.get(`/cf/admin/web-msg/meta/${this.record.id}`).subscribe(res => {
            res.data.isBroadcast = res.data.isBroadcast === '1';
            res.data.channel = [];
            if (res.data.msg === '1') {
              res.data.channel.push('msg');
            }
            if (res.data.email === '1') {
              res.data.channel.push('email');
            }
            if (res.data.sms === '1') {
              res.data.channel.push('sms');
            }
            if (res.data.ding2 === '1') {
              res.data.channel.push('ding2');
            }
            this.i = res.data;
          });
        }
      });
  }

  buildSf() {
    this.schema = {
      properties: {
        msgType: {
          type: 'string',
          title: '消息分类',
          enum: this.msgTypes,
          readOnly: this.record.id ? true : false,
        },
        sysType: {
          type: 'string',
          title: '系统消息类型',
          enum: this.sysTypes,
        },
        msgCode: { type: 'string', title: '编码', ui: { autocomplete: 'off' } },
        msgName: { type: 'string', title: '消息名称', ui: { autocomplete: 'off' } },
        msgRemark: { type: 'string', title: '备注说明', ui: { autocomplete: 'off' } },
        channel: {
          type: 'string',
          title: '发送渠道',
          enum: [
            { label: '站内信', value: 'msg' },
            { label: '钉钉', value: 'ding2' },
            { label: '短信', value: 'sms' },
          ],
          ui: {
            widget: 'checkbox',
            optionalHelp: '钉钉：消息将发送到接收人绑定的钉钉账号;\r \n 短信：将发送到接收人绑定的密保手机号',
            checkAll: true,
          },
        },
      },
      required: ['msgType', 'sysType', 'msgCode', 'msgName'],
      if: {
        properties: { msgType: { enum: ['SYS'] } },
      },
      then: {
        required: ['sysType', 'channel'],
      },
    };
  }

  save(value: any) {
    value.msgCode = value.msgCode.toUpperCase();
    value.msg = value.channel.indexOf('msg') > -1 ? '1' : '0';
    value.ding2 = value.channel.indexOf('ding2') > -1 ? '1' : '0';
    value.email = value.channel.indexOf('email') > -1 ? '1' : '0';
    value.sms = value.channel.indexOf('sms') > -1 ? '1' : '0';

    const req: Observable<string> = this.record.id
      ? this.http.put('/cf/admin/web-msg/meta', value)
      : this.http.post(`/cf/admin/web-msg/meta`, value);

    req.pipe(catchError(err => of(err))).subscribe(res => {
      if (res.status === 200) {
        this.notice.success('成功', '保存成功');
        this.modal.close(true);
      }
    });
  }

  close() {
    this.modal.destroy();
  }
}
